package com.common.data.desensitization.common.handler;

import com.common.data.desensitization.common.annotation.DesensitizationRule;
import com.common.data.desensitization.common.utils.RepeatMaskUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class DesensitizeBankCardHandler implements DesensitizationHandler
{
    @Override
    public String desensitize(String originalValue, DesensitizationRule rule) {
        // 6222 **** **** 1234 (保留前4后4)
        if (originalValue.length() > 8) {
            return originalValue.substring(0, 4) + " " + RepeatMaskUtil.repeatMask(4,rule.maskChar()) + " " + RepeatMaskUtil.repeatMask(4,rule.maskChar()) + " " + originalValue.substring(originalValue.length()-4);
        } else {
            if (originalValue.length() <= Math.min(4, originalValue.length() / 3) + Math.min(4, originalValue.length() / 3)) {
                if (originalValue.length() <= Math.min(4, originalValue.length() / 3)) return originalValue; //只保留前缀
                return RepeatMaskUtil.repeatMask(originalValue.length(), rule.maskChar());
            }
            String prefix = originalValue.substring(0, Math.min(4, originalValue.length() / 3));
            String suffix = originalValue.substring(originalValue.length() - Math.min(4, originalValue.length() / 3));
            if (StringUtils.hasText("")) {
                return prefix + "" + suffix;
            } else {
                int maskedLength = originalValue.length() - Math.min(4, originalValue.length() / 3) - Math.min(4, originalValue.length() / 3);
                return prefix + RepeatMaskUtil.repeatMask(maskedLength, rule.maskChar()) + suffix;
            }
        }
    }
}
